package com.halflife.framework.participant.range;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.halflife.framework.converter.MapHandler;
import com.halflife.framework.domain.Page;
import com.halflife.framework.participant.TreeView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class RoleRangeAdminController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private RoleRangeRepository roleRangeRepository;
    @Resource
    private RangeInfoRepository rangeInfoRepository;

    @RequestMapping("/roleRange/list")
    public String gotoList(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                           HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        int totalCount = roleRangeRepository.selectCount(queryParam);
        List<RoleRange> list = roleRangeRepository.selectListByPage(queryParam);
        page.setTotalCount(totalCount);
        page.setMode(model);
        model.addAttribute("list",list);
        model.addAttribute("queryParam",queryParam);
        return "roleRange/list";
    }

    @RequestMapping("/roleRange/operate")
    public String gotoOperate(Integer id,HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        RoleRange roleRange = new RoleRange();
        if(id!=null){
            roleRange = roleRangeRepository.selectByPrimaryKey(id);
        }
        model.addAttribute("roleRange",roleRange);
        return "roleRange/operate";
    }

    @PostMapping("/roleRange/save")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity save(RoleRange roleRange, HttpServletRequest request,
                              HttpServletResponse response, Model model) {
        try {
            if(roleRange.getId()!=null){
                roleRangeRepository.updateByPrimaryKey(roleRange);
            }else {
                roleRange.init();
                Integer a = roleRangeRepository.insert(roleRange);
            }
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    @DeleteMapping("/roleRange/delete")
    public ResponseEntity setRiderState(Integer id, Integer state) {
        try {
            RoleRange roleRange = new RoleRange();
            roleRange.setId(id);
            roleRange.setValid(Boolean.FALSE);
            roleRangeRepository.updateByPrimaryKeySelective(roleRange);
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    /**
     * 跳转选择权限页面
     * @param queryParam
     * @param page
     * @param response
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/roleRange/rangeSetList")
    public String rangeSetList(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                                  HttpServletRequest request, Model model, Integer roleId) {

        //输出结果字符串
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        //设置参数
        Map<String, Object> param = new HashMap<>();
        //获取父权限
        param.put("valid", true);
        param.put("endSql", "t.rangeInfoId is null");
        List<RangeInfo> parentRangeInfos = rangeInfoRepository.selectAll(param);
        if(parentRangeInfos.size() > 0){

            List<TreeView> parentRangeInfoJson = new ArrayList<>();
            for(RangeInfo rangeInfo: parentRangeInfos){

                if(rangeInfo != null){

//                    parentRangeInfoJson.add(new TreeView(rangeInfo.getId(), rangeInfo.getRangeName(), null));
                    if(sb.length() > 3){
                        sb.append(",");
                    }
                    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                    //转化父权限JSON
                    String str = gson.toJson(new TreeView(rangeInfo.getId(), rangeInfo.getRangeName()));
                    sb.append(str.substring(0, str.length()-1));
                    //转化子权限
                    param.clear();
                    param.put("valid", true);
                    param.put("endSql", "t.rangeInfoId = " + rangeInfo.getId() +  " and t.rangeState = 0");
                    List<RangeInfo> childrenRangeInfo = rangeInfoRepository.selectAll(param);
                    StringBuffer s = new StringBuffer();
                    if(childrenRangeInfo.size() > 0){

                        sb.append(",\"nodes\":");

                        for(RangeInfo children: childrenRangeInfo) {

                            Map<String, Object> m = new HashMap<String, Object>();
                            m.put("endSql", "t.roleId = " + roleId + " and t.rangeInfoId = " + children.getId());
                            int count = roleRangeRepository.selectCount(m);
                            if (count > 0) {

                                s.append(gson.toJson(new TreeView(children.getId(), children.getRangeName(), children.getId())));
                            } else {

                                s.append(gson.toJson(new TreeView(children.getId(), children.getRangeName())));
                            }
                            s.append(",");
                        }
                    }
                    sb.append("[");
                    sb.append(s.toString().substring(0, s.toString().length()-1));
                    sb.append("]");
                    sb.append("}");
                }
            }
        }
        sb.append("]");
        model.addAttribute("data", sb.toString());
        model.addAttribute("roleId", roleId);
        return "roleRange/rangeSetList";
    }

    /**
     *  生成角色权限
     */
    @PostMapping("/roleRange/saveRoleRangeByRangeInfoIds")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity saveRoleRangeByRangeInfoIds(HttpServletRequest request,
                                           HttpServletResponse response, Model model,
                                           String ids, String roleId) {
        try {
            if(ids != null){

                //删除原权限
                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("valid", true);
                paramMap.put("roleId", Integer.valueOf(roleId));
                List<RoleRange> roleRanges = roleRangeRepository.selectAll(paramMap);
                if(roleRanges.size() > 0){

                    for(RoleRange roleRange: roleRanges){

                        roleRangeRepository.deleteByPrimaryKey((int)roleRange.getId());
                    }
                }
                String[] ids_ = ids.split(",");
                if(ids_.length > 0){

                    for(String rangeInfoId : ids_){

                        RangeInfo rangeInfo = rangeInfoRepository.selectByPrimaryKey(Integer.valueOf(rangeInfoId));
                        if(rangeInfo!=null){

                            RoleRange rr = new RoleRange();
                            rr.init();
                            rr.setRangeInfoId(Integer.valueOf(rangeInfoId));
                            rr.setRoleId(Integer.valueOf(roleId));
                            roleRangeRepository.insert(rr);
                        }
                    }
                }
            }

        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

}
